#include <signal.h>
#include <stdio.h>
#include <termios.h>
#include "../ourhdr.h"

#define MAX_PASS_LEN    8

char * getpass0(const* prompt)
{
    static char buf[MAX_PASS_LEN + 1];
    char *ptr;
    sigset_t sig, sigsave;
    struct termios term, termsave;
    FILE *fp;
    int c;
    if((fp=fopen(ctermid(NULL),"r+"))==NULL)
    {
        return (NULL);
    }
    setbuf(fp,NULL);
    sigemptyset(&sig);
    sigaddset(&sig, SIGINT);
    sigaddset(&sig, SIGTSTP);
    sigprocmask(SIG_BLOCK, &sig, &sigsave);
    
    tcgetattr(fileno(fp), &termsave);
    term = termsave;

    term.c_lflag &= ~(ECHO| ECHOE| ECHOK| ECHONL);
    tcsetattr(fileno(fp), TCSAFLUSH, &term);

    fputs(prompt, fp);
    ptr= buf;
    while((c=getc(fp))!=EOF && c!='\n')
    {
        if(ptr < &buf[MAX_PASS_LEN])
        {
            *ptr++=c;
        }
    }
    *ptr = 0;
    putc('\n', fp);
    tcsetattr(fileno(fp),  TCSAFLUSH, &termsave);
    sigprocmask(SIG_SETMASK, &sigsave, NULL);
    fclose(fp);
    return (buf);
}

int main(void)
{
    char *ptr;
    if((ptr = getpass0("Enter password:")) == NULL)
    {
        err_sys("getpass0 error");
    }
    printf("password: %s\n", ptr);

    while(*ptr !=0)
    {
        *ptr++ = 0;
    }
    exit(0);
}